const express = require('express')
const app = express()

app.use(express.json())

const PORT = process.env.PROT || 3000

const courses = [
  { id: 1, name: 'courses1' },
  { id: 2, name: 'courses2' },
  { id: 3, name: 'courses3' }
]

app.get('/', (req, res) => {
  res.send('hello world!!!')
})

app.get('/api/courses', (req, res) => {
  res.send([1, 2, 3])
})

app.get('/api/courses/:id', (req, res) => {
  // res.send(req.params)
  // res.send(req.query)
  const course = courses.find(course => {
    return course.id === parseInt(req.params.id)
  })
  if (!course) { res.status(404).send('The course witdh given ID was nout fund.') }
  res.send(course.name)
})

app.post('/api/courses', (req, res) => {
  const course = {
    id: courses.length + 1,
    name: req.body.name
  }
  courses.push(course)
  res.send(course)
})

app.listen(PORT, () => {
  console.log(`listening on port ${PORT}...`)
})